<template>
    <div class="content">
        <div class="poster">
            <img id="poster" :src="poster" alt="点击按钮重新生成海报">
        </div>

        <div class="link">
            <van-field
                v-model="link"
                center
                readonly
                placeholder="推广地址"
                id="link"
            >
                <template #button>
                    <van-button size="small" type="primary" @click="OnCopy">点击复制</van-button>
                </template>
            </van-field>
        </div>

        <div class="update">
            <van-button type="success" :loading="loading" @click="OnUpdate">重新生成海报</van-button>
        </div>
    </div>
</template>

<script setup>
const { proxy } = getCurrentInstance();

const business = proxy.$business;
const loading = ref(false);
const link = ref('');
const poster = ref(business.value.poster ? business.value.poster_cdn : '');

onBeforeMount(() =>
{
    if(!poster.value || !link.value)
    {
        GetPosterData();
    }
});

const GetPosterData = async () =>
{
    // console.log('发起请求')
    // 获取当前域名 => 方便后面部署服务器时不用修改代码
    const origin = location.origin + '/business/login';

    const params = {
        busid:business.value.id,
        link:origin
    }

    const result = await proxy.$http.post('/sale/index',params);

    if(result.code === 1)
    {
        if(loading.value === true)
        {
            proxy.$success(result.msg);
        }

        poster.value = result.data.poster + '?id=' + Math.random();
        link.value = result.data.link;
    }else{
        proxy.$fail(result.msg);
    }

    if(loading.value === true)
    {
        loading.value = false;
    }
}

const OnUpdate = () =>
{
    loading.value = true;

    GetPosterData();
}

// const OnCopy = async () => {
//     try {
//         // 将指定文本写入系统剪贴板
//         await navigator.clipboard.writeText(link.value);
//         proxy.$success('已复制到剪切板');
//     } catch (e) {
//         proxy.$fail('复制失败，请手动复制');
//     }
// }

const OnCopy = () => {
    // 先创建一个input的元素
    const input = document.createElement('input');

    // 把推广地址赋值给input元素的值里
    input.value = link.value;

    // 在body元素里插入刚才创建的input元素
    document.body.appendChild(input);
    
    // 选中地址
    input.select();

    // 执行复制指令
    document.execCommand('Copy') && proxy.$success('已复制到剪切板');

    // 移除input元素
    document.body.removeChild(input);
}

</script>

<style>
body{
    background-color: #eee;
    padding-top: 10px;
    box-sizing:border-box;
}

.poster{
    width:90%;
    margin: 0 auto;
    border-radius: 5px;
    overflow: hidden;
}

.poster img{
    width: 100%;
}

.link{
    width:90%;
    margin:10px auto;
    display: flex;
    justify-content: center;
    align-content: center;
    align-items: center;
    background:#fff;
    border-radius: 5px;
    overflow: hidden;
}

.update{
    width: 100%;
    text-align: center;
    margin-top:15px;
}

.update .van-button{
    width: 90%;
}

</style>